#!/usr/bin/env python
# -*- coding: utf8 -*-
# title       :
# description :
# author      :'ShenMeng'


from PySide import QtGui, QtCore

from .verbatchmanager import BatchManager
from .task_page import TaskPage

class LocalTaskPage(TaskPage):
    
    def __init__(self, parent=None):
        super(LocalTaskPage, self).__init__(parent=parent)
        self._parent = parent
        self.task_view.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.task_view.customContextMenuRequested.connect(self.show_menu)

        self.context_menu = QtGui.QMenu(self)
        redo_action = self.context_menu.addAction(u'重新开始')
        del_action = self.context_menu.addAction(u'删除任务')
        redo_action.triggered.connect(self.on_redo_action_triggered)
        del_action.triggered.connect(self.on_del_action_triggered)
        

    def show_menu(self, status=1):
        if status:
            if not self.view_model.rowCount():
                return
            if not self.selection_model.hasSelection():
                return
            self.context_menu.exec_(QtGui.QCursor.pos())
            self.context_menu.show()
        else:
            self.context_menu.close()
        self.context_menu.close()
    def on_del_action_triggered(self):
        result = {}
        row_list = [index.row() for index in self.selection_model.selectedRows()]
        row_list.sort()
        row_list.reverse()
        for row in row_list:
            file_name = self.view_model.item(row).text()
            type_data = dict(type=str(self.view_model.item(row, 1).text()), sub=str(self.view_model.item(row, 2).text()))
            result.setdefault(type_data['type'], {}).setdefault(type_data['sub'], []).append(file_name)
        if result:
            root_path = self._parent.root_line.text()
            for batch_type, sub_data in result.iteritems():
                for sub_type, file_list in sub_data.iteritems():
                    manager = BatchManager(batch_type, root_path, sub_type)
                    assignData = manager.assignData
                    okData = manager.okData
                    errorData = manager.errorData
                    taskAssignData = manager.taskAssignData
                    taskOkData = manager.taskOkData
                    taskErrorData = manager.taskErrorData
                    for fileName in file_list:
                        for _data in [assignData, okData, errorData, taskAssignData, taskOkData, taskErrorData]:
                            if _data:
                                if fileName in _data:
                                    if isinstance(_data, list):
                                        _data.remove(fileName)
                                    else:
                                        _data.pop(fileName)
                    # TODO lock 
                    if manager.isAssignDataLock or manager.isOkDataLock or manager.isErrorDataLock:
                        self.show_menu(0)
                        message_box = QtGui.QMessageBox().information(self, u'提示', u'数据被其他用户锁定，请稍后再试！')
                        return
                    manager.setAssignDataLock(1)
                    manager.setOkDataLock(1)
                    manager.setErrorDataLock(1)
                    manager.updateTaskAssignData(taskAssignData, 'w')
                    manager.updateTaskOkData(taskOkData, 'w')
                    manager.updateTaskErrorData(taskErrorData, 'w')
                    manager.updateAssignData(assignData, 'w')
                    manager.updateOkData(okData, 'w')
                    manager.updateErrorData(errorData, 'w')
                    manager.setAssignDataLock(0)
                    manager.setOkDataLock(0)
                    manager.setErrorDataLock(0)
            for row in row_list:
                file_name = self.view_model.item(row).text()
                type_data = dict(type=str(self.view_model.item(row, 1).text()), sub=str(self.view_model.item(row, 2).text()))
                # batch_type = self.view_model.item(row, 1).text()
                for cmdData in self._parent.TaskThread.task_data:
                    if cmdData['type_data'] == type_data and cmdData['file'] == file_name:
                        self._parent.TaskThread.task_data.remove(cmdData)
                        if self.view_model.item(row, 4).text() == 'doing':
                            self._parent.TaskThread.kill = True
                        break
                self.view_model.takeRow(row)
        self.show_menu(0)
        
        
    def on_redo_action_triggered(self):
        result = {}
        root_path = self._parent.root_line.text()
        for index in self.selection_model.selectedRows():
            item = self.view_model.item(index.row())
            type_data = dict(type=str(self.view_model.item(index.row(), 1).text()), 
                             sub=str(self.view_model.item(index.row(), 2).text()))
            # result.setdefault(type_item.text(), {})[item.text()] = dict(row=index.row(), sub=type_sub)
            result.setdefault(type_data['type'], {}).setdefault(type_data['sub'], {})[item.text()] = index.row()
            #result.append(item.text())

        for batch_type, sub_data in result.iteritems():
            for sub_type, data in sub_data.iteritems():
                manager = BatchManager(batch_type, root_path, sub_type)
                # error
                taskErrorData = manager.taskErrorData
                errorData = manager.errorData
                # ok
                taskOkData = manager.taskOkData
                okData = manager.okData
                for fileName in data:
                    for _data in [taskErrorData, errorData, taskOkData, okData]:
                        if _data:
                            if fileName in _data.keys():
                                _data.pop(fileName)

                    #manager.update
                if manager.isOkDataLock or manager.isErrorDataLock:
                    self.show_menu(0)
                    message_box = QtGui.QMessageBox().information(self, u'提示', u'数据被其他用户锁定，请稍后再试！')
                    return
                manager.setErrorDataLock(1)
                manager.setOkDataLock(1)
                manager.updateTaskErrorData(taskErrorData, 'w')
                manager.updateErrorData(errorData, 'w')
                manager.updateTaskOkData(taskOkData, 'w')
                manager.updateOkData(okData, 'w')
                manager.setErrorDataLock(0)
                manager.setOkDataLock(0)
                type_data = dict(type=str(batch_type), sub=str(sub_type))
                for fileName, row in data.iteritems():
                    self.view_model.item(row, 0).setText(fileName)
                    self.view_model.item(row, 0).setIcon(QtGui.QIcon(":icons/clock.png"))
                    self.view_model.item(row, 4).setText('Waiting')
                    item = self.view_model.item(index.row())
                    cmd_str = self._parent.get_cmd(manager, type_data, fileName)
                    self._parent.TaskThread.task_data.append({'cmd':cmd_str, "itemModel":self.view_model,'item':item, 'manager':manager, 'file':fileName, 'type_data': type_data })
        self.show_menu(0)



if __name__ == "__main__":
    app = QtGui.QApplication([])
    bmui = LocalTaskPage()
    bmui.show()
    app.exec_()
        